package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.job.vo.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 *
 * @author Lorine
 * @date 2025-03-08
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 批量保存设备数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //判断设备是否存在
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        if (ObjectUtil.isNull(device)) {
            log.error("设备不存在，iotId:{}", iotId);
            return;
        }

        List<DeviceData> list = new ArrayList<>();
        //解析iotMsgNotifyData封装设备数据
        iotMsgNotifyData.getBody().getServices().forEach(iotMsgService -> {
            Map<String, Object> properties = iotMsgService.getProperties();
            if (ObjectUtil.isEmpty(properties)) {
                log.warn("设备数据为空，iotId:{}", iotId);
                return;
            }
            //处理上报时间日期
            LocalDateTime eventTime = LocalDateTimeUtil.parse(iotMsgService.getEventTime(), "yyyyMMdd'T'HHmmss'Z'")
                    .atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //封装数据
            properties.forEach((key, value) -> {
                DeviceData deviceData = new DeviceData();
                deviceData.setDeviceName(device.getDeviceName());
                deviceData.setIotId(iotId);
                deviceData.setProductKey(device.getProductKey());
                deviceData.setProductName(device.getProductName());
                deviceData.setFunctionId(key);
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setLocationType(device.getLocationType());
                deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
                deviceData.setDeviceDescription(device.getDeviceDescription());
                deviceData.setDataValue(value.toString());
                deviceData.setAlarmTime(eventTime);
                list.add(deviceData);
            });
            //批量保存
            saveBatch(list);

            //存储到redis中deviceDataList
            log.warn("向redis中存入数据");
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, iotId, JSONUtil.toJsonStr(list));
        });
    }

    @Override
    public TableDataInfo<DeviceData> selectPage(DeviceDataPageReqDto deviceDataPageReqDto) {
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        Page<DeviceData> page = new Page<>();
        //设备名称必传
        queryWrapper.eq(DeviceData::getDeviceName, deviceDataPageReqDto.getDeviceName());
        //功能名称必传
        queryWrapper.eq(DeviceData::getFunctionId, deviceDataPageReqDto.getFunctionId());
        //时间范围
        LocalDateTime endTime = deviceDataPageReqDto.getEndTime();
        LocalDateTime startTime = deviceDataPageReqDto.getStartTime();
        queryWrapper.between(ObjectUtil.isNotNull(startTime) && ObjectUtil.isNotNull(endTime), DeviceData::getAlarmTime, startTime, endTime);
        //sql返回结果，只展示主键、名字、身份照号、床位编号
        queryWrapper.select(DeviceData::getAlarmTime, DeviceData::getDataValue);
        page = page(page, queryWrapper);
        //返回分页结果
        TableDataInfo<DeviceData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }
}
